package com.base.system.config.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 登录用户的验证通道
 */
@Component
public class AuthenticationAccessDecisionManager implements AccessDecisionManager {
    /**
     * 对当前匹配的路径执行相应操作和角色匹配
     *
     * @param authentication 保存当前登录用户的信息
     * @param o              获取当前请求对象
     * @param collection     获取的是MyFilter中getAttributes的返回值
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        //匿名token
        //            if ("ROLE_login".equals(attribute.getAttribute()))
        //                if (authentication instanceof AnonymousAuthenticationToken) throw new HttpException("非法请求");
        //                else
        //                    return;//说明已经登录了
        //            //当角色信息合格后，需要匹配角色满足的条件
        //            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        //            for (GrantedAuthority authority : authorities) {
        //                System.err.println(authority.getAuthority());
        //                if (authority.getAuthority().equals(attribute.getAttribute())) return;//只要有一个角色符合就通过，这里可以制定多种条件
        //            }
        for (ConfigAttribute attribute : collection) return;
        throw new AccessDeniedException("非法请求");//没有任何的匹配
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
